<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 头部 -->
        <tree-tools :data="company" :is-show-btn="false" @showDialog="showDialog" />
        <!-- 树形结构 -->
        <el-tree v-loading="loading" :data="list" :props="defaultProps" default-expand-all>
          <template #default="{ data }">
            <tree-tools :data="data" :is-show-btn="true" @showDialog="showDialog" @delDepartment="getDepartmentList()" />
          </template>
        </el-tree>
      </el-card>
    </div>
    <el-dialog
      :title="departForm.id ? '修改部门' : '添加子部门'"
      :visible="dialogVisible"
      width="40%"
      @open="openDialog"
      @close="closeDialog"
    >
      <el-form ref="departForm" :model="departForm" :rules="departRules" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departForm.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编号" prop="code">
          <el-input v-model="departForm.code" placeholder="请输入部门编号" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="departForm.manager" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="departForm.introduce" placeholder="请输入部门介绍" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList, getManagerList, addDepartment, getDepartmentDetail, updateDepartment } from '@/api/department'
import TreeTools from './components/tree-tools'
import { recurTransTree } from '@/utils/transTree'
export default {
  components: {
    TreeTools
  },
  data() {
    const validateName = (rules, value, cb) => {
      // rules: 校验规则相关的信息，基本用不到
      // value：校验规则所校验的表单项的值
      // cb：它是一个函数
      //     如果校验通过：cb()
      //     如果校验不通过：cb(new Error('校验不通过提示信息'))
      let broArr
      if (this.departForm.id) {
        if (this.currentData.name === value) {
          cb()
          return
        }
        broArr = this.originList.filter(item => item.pid === this.currentData.pid)
      } else {
        broArr = this.originList.filter(item => item.pid === this.currentData.id)
      }
      const isSame = broArr.some(item => item.name === value)
      if (isSame) {
        cb(new Error('同级部门名称不能相同'))
      } else {
        cb()
      }
    }
    const validateCode = (rules, value, cb) => {
      if (this.departForm.id && this.currentData.code === value) {
        cb()
        return
      }
      const isSame = this.originList.some(item => item.code === value)
      if (isSame) {
        cb(new Error('部门编码不能相同'))
      } else {
        cb()
      }
    }
    return {
      list: [{
        name: '技术部',
        manager: '张三',
        children: [{
          name: '研发部',
          manager: '李四',
          children: [{
            name: '前端研发部',
            manager: '王五'
          }]
        }]
      }],
      defaultProps: {
        label: 'name'
      },
      company: {
        name: '传智教育',
        manager: '负责人',
        id: ''
      },
      dialogVisible: false,
      departForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      departRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: ['blur', 'change'] }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      currentData: {},
      originList: [],
      managerList: [],
      loading: false
    }
  },
  async created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      this.loading = true
      try {
        const res = await getDepartmentList()
        // console.log(res.data.depts)
        // this.list = this.transTree(res.data.depts)
        this.list = recurTransTree(res.data.depts, '')
        this.originList = res.data.depts
        this.loading = false
      } catch {
        this.loading = false
      }
    },
    async showDialog(data, type) {
      this.currentData = data
      this.dialogVisible = true
      if (type === 'edit') {
        const res = await getDepartmentDetail(this.currentData.id)
        this.departForm = res.data
      }
    },
    closeDialog() {
      this.dialogVisible = false
      this.$refs.departForm.resetFields()
      this.departForm = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    async openDialog() {
      const res = await getManagerList()
      this.managerList = res.data
    },
    submit() {
      this.$refs.departForm.validate(async valid => {
        if (!valid) return
        if (this.departForm.id) {
          await updateDepartment(this.departForm)
        } else {
          await addDepartment({
            ...this.departForm,
            pid: this.currentData.id
          })
        }
        const msg = this.departForm.id ? '修改子部门成功' : '添加子部门成功'
        this.$message.success(msg)
        this.dialogVisible = false
        this.getDepartmentList()
      })
    }
  }
}

</script>

<style></style>
